<template>
  <div class="order-container">
    <!-- 筛选工具栏 -->
    <a-card class="filter-card" :bordered="false">
      <a-form layout="inline" :model="filterForm">
        <a-form-item label="订单状态">
          <a-select
            v-model="filterForm.orderStatus"
            placeholder="全部状态"
            allow-clear
            @change="handleFilter"
          >
            <a-option
              v-for="item in orderStatusOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            />
          </a-select>
        </a-form-item>

        <a-form-item label="支付状态">
          <!--          <a-select-->
          <!--            v-model="filterForm.paymentStatus"-->
          <!--            placeholder="全部状态"-->
          <!--            allow-clear-->
          <!--            @change="handleFilter"-->
          <!--          >-->
          <!--            <a-option-->
          <!--              v-for="item in paymentStatusOptions"-->
          <!--              :key="item.value"-->
          <!--              :value="item.value"-->
          <!--              :label="item.label"-->
          <!--            />-->
          <!--          </a-select>-->
        </a-form-item>

        <a-form-item>
          <a-input-search
            v-model="filterForm.searchKey"
            placeholder="订单号/收货人"
            allow-clear
            search-button
            @search="handleFilter"
          />
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 订单列表 -->
    <div class="order-list">
      <a-card
        v-for="order in orderList"
        :key="order.orderId"
        class="order-item"
        hoverable
      >
        <div class="order-header">
          <div class="order-meta">
            <span class="order-time">{{ formatTime(order.createTime) }}</span>
            <span class="order-id">订单号：{{ order.orderId }}</span>
          </div>
          <a-tag :color="getOrderStatusColor(order.orderStatus)">
            {{ getOrderStatusText(order.orderStatus) }}
          </a-tag>
        </div>

        <a-divider />

        <div class="order-content">
          <!-- 商品信息 -->
          <div class="goods-section">
            <div class="goods-main">
              <a-image
                :src="order.productInfo?.coverImage"
                :preview="true"
                width="100"
                height="100"
                class="goods-image"
                fit="cover"
              />
              <div class="goods-info">
                <h3 class="goods-title">{{ order.productInfo?.title }}</h3>
                <p class="goods-desc">{{ order.productInfo?.description }}</p>
                <div class="goods-meta">
                  <span class="goods-price"
                    >¥{{ order.productInfo?.price?.toFixed(2) }}</span
                  >
                  <span class="goods-quantity">x1</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 订单摘要 -->
          <div class="order-summary">
            <div class="summary-item">
              <span class="label">支付状态：</span>
              <a-tag :color="order.paymentStatus ? 'green' : 'red'">
                {{ order.paymentStatus ? "已支付" : "待支付" }}
              </a-tag>
            </div>
            <div class="summary-item">
              <span class="label">订单总额：</span>
              <span class="total-amount"
                >¥{{ order.totalAmount?.toFixed(2) }}</span
              >
            </div>
            <div class="summary-item address">
              <icon-location class="address-icon" />
              <div class="address-info">
                <div class="receiver">
                  {{ order.addressInfo?.receiverName }}
                  {{ order.addressInfo?.mobile }}
                </div>
                <div class="detail">
                  {{ order.addressInfo?.province
                  }}{{ order.addressInfo?.city }}
                  {{ order.addressInfo?.district
                  }}{{ order.addressInfo?.detailAddress }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="order-actions">
          <a-button
            type="outline"
            size="small"
            @click="viewDetail(order.orderId)"
          >
            订单详情
          </a-button>
          <a-button
            v-if="!order.paymentStatus"
            type="primary"
            size="small"
            @click="handlePayment(order.orderId)"
          >
            立即支付
          </a-button>
          <a-button
            v-if="order.orderStatus === 0"
            type="outline"
            status="danger"
            size="small"
            @click="cancelOrder(order.orderId)"
          >
            取消订单
          </a-button>
        </div>
      </a-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <a-pagination
        v-model="pagination.current"
        :total="pagination.total"
        :page-size="pagination.size"
        :page-size-options="[5, 10, 20]"
        show-page-size
        show-total
        @change="handlePagination"
        @page-size-change="handlePageSizeChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import dayjs from "dayjs";
import { OrderControllerService, ProductControllerService } from "@/generated";
import { useRouter } from "vue-router";

const router = useRouter();

interface ProductInfo {
  productId: string;
  title: string;
  price: number;
  coverImage: string;
  description: string;
}

interface AddressInfo {
  receiverName: string;
  mobile: string;
  province: string;
  city: string;
  district: string;
  detailAddress: string;
}

interface Order {
  orderId: string;
  userId: string;
  totalAmount: number;
  paymentStatus: number;
  orderStatus: number;
  createTime: string;
  deliveryAddress: string;
  productId: string;
  productInfo?: ProductInfo;
  addressInfo?: AddressInfo;
}

// 筛选表单
const filterForm = reactive({
  orderStatus: null,
  // paymentStatus: null,
  searchKey: "",
});

// 分页参数
const pagination = reactive({
  current: 1,
  size: 5,
  total: 0,
});

const orderList = ref<Order[]>([]);
const loading = ref(false);

// 状态选项
const orderStatusOptions = [
  { value: 0, label: "待发货" },
  { value: 1, label: "已发货" },
  { value: 2, label: "已完成" },
];

const paymentStatusOptions = [
  { value: 0, label: "待支付" },
  { value: 1, label: "已支付" },
];

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true;
    const res = await OrderControllerService.getOrderListByPage({
      pageNumber: pagination.current,
      pageSize: pagination.size,
      paymentStatus: 0,
      ...filterForm,
    });

    if (res.code === 0 && res.data) {
      const enhancedOrders = await Promise.all(
        res.data.records.map(async (order: any) => {
          try {
            const productRes = await ProductControllerService.getProductById(
              order.productId
            );
            const addressInfo = JSON.parse(order.deliveryAddress);
            return {
              ...order,
              productInfo: productRes.data,
              addressInfo,
            };
          } catch (error) {
            console.error("数据加载失败:", error);
            return order;
          }
        })
      );

      orderList.value = enhancedOrders;
      pagination.total = res.data.total;
    }
  } catch (error) {
    Message.error("获取订单列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理筛选
const handleFilter = () => {
  pagination.current = 1;
  fetchOrders();
};

// 分页处理
const handlePagination = (page: number) => {
  pagination.current = page;
  fetchOrders();
};

const handlePageSizeChange = (size: number) => {
  pagination.size = size;
  fetchOrders();
};

// 地址格式化
const formatAddress = (addressStr: string) => {
  try {
    return JSON.parse(addressStr);
  } catch {
    return null;
  }
};

// 状态显示
const getOrderStatusColor = (status: number) => {
  switch (status) {
    case 0:
      return "orange";
    case 1:
      return "arcoblue";
    case 2:
      return "green";
    default:
      return "gray";
  }
};

const getOrderStatusText = (status: number) => {
  switch (status) {
    case 0:
      return "待发货";
    case 1:
      return "已发货";
    case 2:
      return "已完成";
    default:
      return "未知状态";
  }
};

// 时间格式化
const formatTime = (time: string) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 订单操作
const viewDetail = (orderId: string) => {
  router.push(`/order/detail/${orderId}`);
};

const handlePayment = (orderId: string) => {
  router.push(`/payment/paymentView/${orderId}`);
};

const cancelOrder = async (orderId: string) => {
  try {
    await Modal.confirm({
      title: "确认取消订单",
      content: "确定要取消该订单吗？",
      okText: "确认",
      cancelText: "取消",
    });

    const res = await OrderControllerService.deleteOrder(orderId);
    if (res.code === 0) {
      Message.success("取消成功");
      await fetchOrders();
    }
  } catch (error) {
    // 取消操作
  }
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped lang="scss">
.order-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;

  .filter-card {
    margin-bottom: 16px;
    background-color: var(--color-bg-2);
    border-radius: 8px;

    :deep(.arco-form-item) {
      margin-bottom: 0;
      margin-right: 16px;
    }
  }

  .order-list {
    display: grid;
    gap: 16px;
  }

  .order-item {
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.2s ease;
    border: 1px solid var(--color-border-2);

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      transform: translateY(-2px);
    }

    .order-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 24px;
      background: var(--color-bg-2);

      .order-meta {
        .order-time {
          font-size: 12px;
          color: var(--color-text-3);
          margin-bottom: 4px;
        }

        .order-id {
          font-size: 14px;
          color: var(--color-text-1);
          font-weight: 500;
        }
      }
    }

    .order-content {
      display: grid;
      grid-template-columns: 1.5fr 1fr;
      gap: 24px;
      padding: 24px;

      .goods-section {
        .goods-main {
          display: flex;
          gap: 16px;
          align-items: flex-start;

          .goods-image {
            border-radius: 6px;
            overflow: hidden;
            flex-shrink: 0;
          }

          .goods-info {
            flex: 1;

            .goods-title {
              margin: 0 0 8px;
              font-size: 16px;
              font-weight: 600;
              color: var(--color-text-1);
              line-height: 1.4;
            }

            .goods-desc {
              margin: 0 0 12px;
              font-size: 13px;
              color: var(--color-text-3);
            }

            .goods-meta {
              display: flex;
              align-items: center;
              gap: 12px;

              .goods-price {
                color: rgb(var(--red-6));
                font-size: 16px;
                font-weight: 600;
              }

              .goods-quantity {
                color: var(--color-text-3);
                font-size: 14px;
              }
            }
          }
        }
      }

      .order-summary {
        border-left: 1px solid var(--color-border-2);
        padding-left: 24px;

        .summary-item {
          margin-bottom: 16px;

          &.address {
            display: flex;
            gap: 8px;
            align-items: flex-start;

            .address-icon {
              margin-top: 4px;
              color: var(--color-text-3);
              font-size: 16px;
            }

            .address-info {
              .receiver {
                font-weight: 500;
                margin-bottom: 4px;
              }

              .detail {
                font-size: 13px;
                color: var(--color-text-3);
                line-height: 1.5;
              }
            }
          }

          .label {
            color: var(--color-text-3);
            margin-right: 8px;
          }

          .total-amount {
            color: rgb(var(--red-6));
            font-size: 18px;
            font-weight: 600;
          }
        }
      }
    }

    .order-actions {
      padding: 16px 24px;
      border-top: 1px solid var(--color-border-2);
      display: flex;
      gap: 12px;
      justify-content: flex-end;
    }
  }

  .pagination-container {
    margin-top: 24px;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .order-container {
    padding: 0 12px;

    .order-content {
      grid-template-columns: 1fr !important;
      gap: 16px !important;
      padding: 16px !important;

      .order-summary {
        border-left: none !important;
        padding-left: 0 !important;
        padding-top: 16px;
        border-top: 1px solid var(--color-border-2);
      }
    }

    .goods-main {
      flex-direction: column;
      align-items: flex-start !important;

      .goods-image {
        width: 100% !important;
        height: auto !important;
      }
    }
  }
}
</style>
